package com.softdev.controller;

import com.softdev.common.R;
import com.softdev.dto.UserDto;
import com.softdev.pojo.LoginParam;
import com.softdev.pojo.User;
import com.softdev.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Api("用户操作")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation("登录")
    @PostMapping("/login")
    public R<Map<String , String>> login(@RequestBody LoginParam param , HttpServletRequest request) {

        String token = userService.login(param.getUsername() , param.getPassword() , request);

        Map<String , String> map = new HashMap<>();
        map.put("token" , token);
        map.put("tokenHead" , tokenHead);

        return R.success(map);

    }

    @ApiOperation("登出")
    @PostMapping("/logout")
    public R<String> logout (HttpServletRequest request, HttpServletResponse response) {
        return userService.logout(request , response);
    }

    @ApiOperation("查看个人信息")
    @GetMapping
    public R<User> get() {

        User user = userService.get();

        return R.success(user);
    }

    @ApiOperation("修改个人信息")
    @PutMapping
    public R<String> update(@RequestBody User user) {

        if (userService.update(user)) {
            return R.success("修改成功！");
        }

        return R.error("修改失败...");
    }

    @ApiOperation("新增员工")
    @PreAuthorize("hasRole('ROLE_manager')")
    @PostMapping
    public R<String> add(@RequestBody UserDto userDto) {

        if (userService.add(userDto)) {
            return R.success("员工新增成功！");
        }

        return R.error("员工新增失败...");
    }

    @ApiOperation(
            value = "分页查看所有员工" ,
            notes = "skillIds为空查找全部，不为空则根据skillId进行筛选"
    )
    @PreAuthorize("hasRole('ROLE_manager')")
    @GetMapping("/page")
    public R<Page<User>> page(int page , int size , Long[] skillIds) {

        Page<User> users = userService.page(page, size, skillIds);

        return R.success(users);
    }

}
